package com.app.controller;

import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import com.app.common.Result;
import com.app.model.*;
import com.app.server.*;
import com.app.utils.CommonHelp;
import com.app.utils.SMSUtils;
import com.app.utils.TokenUtils;
import com.app.vo.AnimalRescueVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 * 野生动物救助
 */
@Slf4j
@RestController
@RequestMapping("/sbbz/animalRescue")
public class AnimalRescueController {
    @Autowired
    private AnimalRescueService animalRescueService;

    @Autowired
    private AdminUserService adminUserService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private UnitsRescueService unitsRescueService;
    @Autowired
    private RecordFileService recordFileService;
    @Autowired
    private UserService userService;
    @Resource
    private SMSUtils smsUtils;

    // 查询列表
    @GetMapping("/getAnimalRescueList")
    public Result getAnimalRescueList(@RequestParam(defaultValue = "0") Integer page,
                                      @RequestParam(defaultValue = "10") Integer limit, Integer departmentId, Integer type, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String adminStringId = TokenUtils.verify(token);
        if (adminStringId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        Integer adminId = Integer.valueOf(adminStringId);
        AdminUserModel adminUser = adminUserService.getById(adminId);
        if (adminUser == null) {
            return Result.error(406, "用户不存在");
        }
        Integer roleId = adminUser.getRoleId();
        Integer unitsId = adminUser.getUnitsId();
        //如果是超级管理员查全部
        if (roleId == 1) {
            AnimalRescueVo animalRescueVo = animalRescueService.getAnimalRescueList(page, limit, departmentId, type);
            return Result.success(animalRescueVo);
        }
        //根据当前登录的单位查询列表
        AnimalRescueVo animalRescueVo = animalRescueService.getAnimalRescueByUnitsList(page, limit, departmentId, type, unitsId);

        return Result.success(animalRescueVo);
    }

    //根据id查询
    @GetMapping("/getAnimalRescueById")
    public Result getAnimalRescueById(Integer id) {
        AnimalRescueModel animalRescue = animalRescueService.getAnimalRescueById(id);
        if (animalRescue == null) {
            return Result.success("数据不存在");
        }
        QueryWrapper<CategoryModel> qw = new QueryWrapper<>();
        qw.eq("id", animalRescue.getType());
        CategoryModel category = categoryService.getOne(qw);
        animalRescue.setTypeText(category.getName());
        Integer allocationStatus = animalRescue.getAllocationStatus();
        if (allocationStatus == 3) {
            //处理状态为3时 带处理对象
            animalRescue = animalRescueService.setRescueHandle(animalRescue);
        }
        return Result.success(animalRescue);
    }

    //根据野生动物种类查询
    @GetMapping("/getAnimalRescueByType")
    public Result getAnimalRescueByType(Integer page, Integer limit, Integer type) {
        AnimalRescueVo animalRescueList = animalRescueService.getAnimalRescueByType(page, limit, type);
        return Result.success(animalRescueList);
    }

    //获取动物类型
    @GetMapping("/getAnimalType")
    public Result getAnimalType() {
        List<CategoryModel> animalTypeList = categoryService.getAnimalType();
        return Result.success(animalTypeList);
    }

    //分配动物救助
    @GetMapping("/allocation")
    public Result updateAllocation(Integer id, @RequestParam("unitsId") Integer[] unitsIds, HttpServletRequest request) {
        AnimalRescueModel animalRescue = new AnimalRescueModel();
        animalRescue.setId(id);
        animalRescue.setAllocationStatus(2);
        animalRescueService.updateById(animalRescue);
        for (Integer unitsId : unitsIds) {
            UnitsRescueModel unitsRescue = new UnitsRescueModel();
            unitsRescue.setRescueId(id);
            unitsRescue.setUnitsId(unitsId);
            unitsRescue.setCreateTime(CommonHelp.getNowTimestamp());
            unitsRescueService.save(unitsRescue);
        }
        List<Integer> unitsIdsList = Arrays.asList(unitsIds);
        QueryWrapper<AdminUserModel> adminUserModelQueryWrapper = new QueryWrapper<>();
        adminUserModelQueryWrapper.in("units_id", unitsIdsList);
        List<AdminUserModel> userModelList = adminUserService.list(adminUserModelQueryWrapper);
        for (AdminUserModel adminUserModel : userModelList) {
            if (adminUserModel != null && adminUserModel.getPhone() != null) {
                if (PhoneUtil.isMobile(adminUserModel.getPhone())) {
                    synchronized (this.smsUtils) {
                        this.smsUtils.allocationSms(adminUserModel.getPhone(), adminUserModel.getRealName());
                    }
                }
            }
        }
        return Result.success("分发成功");
    }

    //新增和修改
    @PostMapping("/addAndUpdateAnimalRescue")
    public Result addAndUpdateAnimalRescue(@RequestBody AnimalRescueModel animalRescueModel, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String openId = TokenUtils.verify(token);
        UserModel user = userService.getUserByOpenid(openId);
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        if (StrUtil.isBlank(user.getAreaId())) {
            return Result.error(407, "请先完善个人信息");
        }
        AnimalRescueModel animalRescue = animalRescueService.getById(animalRescueModel.getId());
        if (animalRescue != null) {
            animalRescueModel.setUpdateTime(CommonHelp.getNowTimestamp());
            animalRescueService.updateById(animalRescueModel);
            return Result.success("修改成功");
        } else {
            animalRescueModel.setUsername(user.getName());
            animalRescueModel.setOpenId(user.getOpenId());
            animalRescueModel.setCreateTime(CommonHelp.getNowTimestamp());
            StringBuilder s1 = new StringBuilder();
            if (animalRescueModel.getPic() != null && animalRescueModel.getPic().length > 0) {
                String[] pic = animalRescueModel.getPic();
                for (int i = 0; i < pic.length; i++) {
                    String[] split = pic[i].split("/");
                    int length = split.length;
                    RecordFileModel recordFileModel = new RecordFileModel();
                    recordFileModel.setName(split[length - 1]);
                    recordFileModel.setUrl(pic[i]);
                    recordFileModel.setFileType(1);
                    recordFileModel.setCreateTime(CommonHelp.getNowTimestamp());
                    recordFileService.insert(recordFileModel);
                    s1.append(recordFileModel.getId()).append(",");
                }
            }
            if (animalRescueModel.getVideo() != null && animalRescueModel.getVideo().length > 0) {
                String[] pic = animalRescueModel.getVideo();
                for (int i = 0; i < pic.length; i++) {
                    String[] split = pic[i].split("/");
                    int length = split.length;
                    RecordFileModel recordFileModel = new RecordFileModel();
                    recordFileModel.setName(split[length - 1]);
                    recordFileModel.setUrl(pic[i]);
                    recordFileModel.setFileType(2);
                    recordFileModel.setCreateTime(CommonHelp.getNowTimestamp());
                    recordFileService.insert(recordFileModel);
                    if (i == pic.length - 1) {
                        s1.append(recordFileModel.getId());
                    } else {
                        s1.append(recordFileModel.getId()).append(",");
                    }
                }
            }
            animalRescueModel.setFileId(s1.toString());
            animalRescueService.save(animalRescueModel);
            CategoryModel category = categoryService.getById(animalRescueModel.getType());
            animalRescueModel.setTypeText(category.getName());
            QueryWrapper<AdminUserModel> adminUserModelQueryWrapper = new QueryWrapper<>();
            adminUserModelQueryWrapper.eq("role_id", 1);
            List<AdminUserModel> modelList = adminUserService.list(adminUserModelQueryWrapper);
            for (AdminUserModel adminUserModel : modelList) {
                if (adminUserModel != null && adminUserModel.getPhone() != null) {
                    if (PhoneUtil.isMobile(adminUserModel.getPhone())) {
                        synchronized (this.smsUtils) {
                            this.smsUtils.animalRescueSms(adminUserModel.getPhone(), animalRescueModel.getTypeText(), animalRescueModel.getPosition(), user.getPhone());
                        }
                    }
                }
            }
        }
        return Result.success("操作成功");
    }

    //根据id删除
    @GetMapping("/delAnimalRescue")
    public Result delAnimalRescue(Integer id) {
        animalRescueService.removeById(id);
        return Result.success("删除成功");
    }

}
